<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <title>SkyPilot Dashboard</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
        integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <style>
        .table-no-stripes tbody tr:nth-of-type(even) {
            background-color: transparent;
        }

        .table-hover-selected tbody tr:hover {
            background-color: #f5f5f5;
        }

        .footer {
            font-size: 14px;
            color: #777;
            margin-top: 20px;
        }

        body {
            margin-top: 20px;
        }

        .bg-light {
            color: #212529;
            /* for some reason not in bootstrap? */
        }

        .fixed-header-table thead {
            position: sticky;
            top: 0;
            background-color: #f8f9fa;
            /* Replace with your desired background color */
            color: #000000;
            /* Replace with your desired text color */
            z-index: 1;
        }
        .clickable {
           cursor: pointer; /* This makes the cursor a pointer when hovering over the element */
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data.min.js"></script>

</head>

<body>
    <div class="container">
        <header>
            <h1>Managed jobs</h1>
            <p class="text-muted mt-4" id="last-updated"></p>
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="refresh-toggle" checked>
                <label class="form-check-label" for="refresh-toggle">Auto-refresh (every 30s)</label>
            </div>
        </header>

        <table class="table table-hover table-hover-selected fixed-header-table" id="jobs-table">
            <thead>
                <tr>
                    {% for column in columns %}
                    <th>{{ column }}</th>
                    {% endfor %}
                </tr>
            </thead>
            <tbody>
                {% for row in rows %}
                <tr class="{% if row[2] == '' %}folder{% endif %}{% if row[1] == ' \u21B3' %}folded{% endif %}">
                    <td>{% if row[2] == '' %}<span class="clickable">▶</span>{% endif %}</td>
                    <td>{{ row[1]|string|replace(' \u21B3', '') }}</td>
                    <td>{{ row[2] }}</td>
                    <td>{{ row[3] }}</td>
                    <td>{{ row[4] }}</td>
                    <td>{{ row[5] }}</td>
                    <td>{{ row[6] }}</td>
                    <td>{{ row[7] }}</td>
                    <td>{{ row[8] }}</td>
                    <td>
                        <!-- https://getbootstrap.com/docs/4.0/components/badge/ -->
                        {% if row[9].startswith('RUNNING') %}
                        <span class="badge bg-primary">{{ row[9].split()[0] }}</span>{{ row[9][row[9].split()[0]|length:] }}
                        {% elif row[9].startswith('PENDING') or row[9].startswith('SUBMITTED') %}
                        <span class="badge bg-light">{{ row[9].split()[0] }}</span>{{ row[9][row[9].split()[0]|length:] }}
                        {% elif row[9].startswith('RECOVERING') or row[9].startswith('CANCELLING') or row[9].startswith('STARTING') %}
                        <span class="badge bg-info">{{ row[9].split()[0] }}</span>{{ row[9][row[9].split()[0]|length:] }}
                        {% elif row[9].startswith('SUCCEEDED') %}
                        <span class="badge bg-success">{{ row[9].split()[0] }}</span>{{ row[9][row[9].split()[0]|length:] }}
                        {% elif row[9].startswith('CANCELLED') %}
                        <span class="badge bg-secondary">{{ row[9].split()[0] }}</span>{{ row[9][row[9].split()[0]|length:] }}
                        {% elif row[9].startswith('FAILED') %}
                        <span class="badge bg-warning">{{ row[9].split()[0] }}</span>{{ row[9][row[9].split()[0]|length:] }}
                        {% else %}
                        {{ row[9] }}
                        {% endif %}
                    </td>
                    <td>{{ row[10] }}</td>
                    <td>{{ row[11] }}</td>
                    <td>{{ row[12] }}</td>
                    <td>{{ row[13] }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    <script>
        // Folder toggle for pipelines, this will fold/unfold the rows for
        // a pipeline and its tasks.
        document.querySelectorAll('.folder').forEach(function (folder) {
            folder.addEventListener('click', function () {
                let plusSign = folder.querySelector('.clickable');
                let folderIndex = Array.from(document.querySelectorAll('.folder')).indexOf(folder);

                if (!plusSign) {
                    plusSign = document.createElement('span');
                    plusSign.classList.add('clickable');
                    folder.children[0].prepend(plusSign); // Ensure the clickable span is the first child of the folder cell
                }

                let displayState = 'none';
                if (plusSign.textContent === '▶') {
                    plusSign.textContent = '▼'; // Change to downward-pointing triangle
                    displayState = '';
                    localStorage.setItem('folderState' + folderIndex, 'expanded');
                } else {
                    plusSign.textContent = '▶'; // Change back to right-pointing triangle
                    localStorage.setItem('folderState' + folderIndex, 'collapsed');
                }

                let next = folder.nextElementSibling;
                while (next && next.classList.contains('folded')) {
                    next.style.display = displayState;
                    next = next.nextElementSibling;
                }
            });
        });

        document.addEventListener("DOMContentLoaded", function () {
            // Setting initial fold state for each folder
            document.querySelectorAll('.folder').forEach(function (folder, index) {
                let storedState = localStorage.getItem('folderState' + index);
                let plusSign = folder.querySelector('.clickable');
                let next = folder.nextElementSibling;
                if (storedState === 'expanded') {
                    plusSign.textContent = '▼';
                    while (next && next.classList.contains('folded')) {
                        next.style.display = '';  // Show
                        next = next.nextElementSibling;
                    }
                } else {
                    plusSign.textContent = '▶';
                    while (next && next.classList.contains('folded')) {
                        next.style.display = 'none';  // Hide initially
                        next = next.nextElementSibling;
                    }
                }
            });
            document.querySelectorAll('.folded').forEach(function (folded) {
                if (!folded.previousElementSibling.querySelector('.clickable').textContent.includes('▼')) {
                    folded.style.display = 'none'; // Make sure these rows are initially hidden unless state is expanded
                }
            });
        });
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            var timestamp = "{{ last_updated_timestamp }}";  // Get the UTC timestamp from the template
            var localTimestamp = moment.utc(timestamp).tz(moment.tz.guess()).format('YYYY-MM-DD HH:mm:ss z');
            document.getElementById("last-updated").textContent = "Last updated: " + localTimestamp;
        });
    </script>
    <script>
        // Function to handle toggle of auto-refresh
        // Retrieve the previous state from localStorage
        var storedRefreshState = localStorage.getItem("refreshState");
        var refreshToggle = document.getElementById("refresh-toggle");
        if (storedRefreshState === 'true' || storedRefreshState === null) {
            refreshToggle.checked = true;
        } else {
            refreshToggle.checked = false;
        }
        // Add event listener to the toggle switch
        function handleAutoRefresh() {
            localStorage.setItem("refreshState", refreshToggle.checked);
            // Check the state of the toggle switch
            if (refreshToggle.checked) {
                // Auto-refresh is enabled
                refreshInterval = setInterval(function () {
                    location.reload();
                }, 30000); // 30 seconds in milliseconds
            } else {
                // Auto-refresh is disabled
                clearInterval(refreshInterval);
            }
        }
        refreshToggle.addEventListener("change", handleAutoRefresh);
        handleAutoRefresh();
    </script>
    <script>
        function filterStatus(status) {
            var rows = document.querySelectorAll("#spot-jobs-table tbody tr");
            rows.forEach(function (row) {
                var statusCell = row.querySelector("td:nth-child(9)");

                if (status === '' || statusCell.textContent === status) {
                    row.style.display = "";
                } else {
                    row.style.display = "none";
                }
            });
        }
    </script>

</body>

</html>
